package com.yiliao.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.yiliao.service.PushMsgService;
import com.yiliao.util.DateUtils;
import com.yiliao.util.PushUtil;

@Service("pushMsgService")
public class PushMsgServiceImpl extends ICommServiceImpl implements PushMsgService {

	@Override
	public JSONObject getPushMsgList(int page) {
		try {
			
			String qSql = " SELECT u.t_idcard,u.t_nickName,u.t_phone,m.t_message_content,DATE_FORMAT(m.t_create_time,'%Y-%m-%d %T') AS t_create_time FROM t_message m LEFT JOIN t_user u ON m.t_user_id = u.t_id ORDER BY t_create_time DESC LIMIT ? ,10;";
			
			List<Map<String, Object>> dataList = this.getFinalDao().getIEntitySQLDAO().findBySQLTOMap(qSql, (page-1)*10);
			
			for(Map<String, Object> m : dataList){
				if(null == m.get("t_nickName")){
					m.put("t_nickName", "聊友:"+m.get("t_phone").toString().substring(m.get("t_phone").toString().length()-4));
				}
				m.remove("t_phone");
			}
			String cSql = " SELECT COUNT(t_id) AS total FROM t_message ";
			Map<String, Object> totalMap = this.getFinalDao().getIEntitySQLDAO().findBySQLUniqueResultToMap(cSql);
			JSONObject json = new JSONObject();
			json.put("total", totalMap.get("total"));
			json.put("rows", dataList);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * 全服推送(non-Javadoc)
	 * @see com.yiliao.service.PushMsgService#addWholeServicePush(java.lang.String)
	 */
	@Override
	public void addWholeServicePush(Integer t_user_role,String push_msg) {
		try {
			//得到总用户数
			String qSql = "SELECT t_id FROM t_user ";
			if(t_user_role != -1) {
				qSql = qSql + "WHERE  t_role = "+ t_user_role;
			}
			List<Map<String, Object>> dataList = this.getFinalDao().getIEntitySQLDAO().findBySQLTOMap(qSql);
			List<String> pushList=new ArrayList<String>();
			StringBuffer messageSql = new StringBuffer();
			messageSql.append("INSERT INTO t_message (t_user_id, t_message_content, t_create_time, t_is_see) VALUES ");
			int count=1;
			int page =1;
			int pageCount = dataList.size()%1000 == 0? dataList.size() /1000:dataList.size()/1000+1;
			int yushu=dataList.size()%1000;
			for (Map<String, Object> m : dataList) {
				//存储消息
				if(count==1000||(yushu==count&&pageCount==page)) {
					messageSql.append("("+m.get("t_id")+",'"+push_msg+"',now(),0)");
					this.executeSql(messageSql.toString());
					messageSql = new StringBuffer();
					messageSql.append("INSERT INTO t_message (t_user_id, t_message_content, t_create_time, t_is_see) VALUES ");
					count=1;
					page++;
					PushUtil.sendAllPush(pushList, push_msg);
					pushList.clear();
				}else {
					messageSql.append("("+m.get("t_id")+",'"+push_msg+"',now(),0),");
				}
				count++;
				pushList.add(m.get("t_id").toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
